﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using ReportingSystem.Model;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace ReportingSystem
{
    public class JWTSetUp
    {
        public static string GenerateJWT(string securityKey,string issuer,string audience)
        {
            // 1. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 2. 定义需要使用到的Claims
            var claims = new[]
            {
                ////sub user Id
                new Claim(JwtRegisteredClaimNames.Sub, "1"),
                ////role Admin
                //new Claim(ClaimTypes.Role, "Admin"),
                new Claim(ClaimTypes.NameIdentifier, "1")
            };

            // 3. 从 appsettings.json 中读取SecretKey
            //var asas = _configuration["JWT:SecurityKey"];
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上组件，生成token
            var token = new JwtSecurityToken(
                //_configuration["JWT:Issuer"],    //Issuer
                //_configuration["JWT:Audience"],  //Audience
                issuer,
                audience,
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddDays(1),         //expires
                signingCredentials
            );
            // 6. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return jwtToken;
        }

    }
}
